package logic

import (
	"Junior_two/subject/cart/cartrpc/dao"
	"Junior_two/subject/cart/cartrpc/model"
	"Junior_two/subject/cart/cartrpc/utils"
	"context"
	"fmt"
	"github.com/astaxie/beego/logs"
	"net/http"

	"Junior_two/subject/cart/cartrpc/internal/svc"
	"Junior_two/subject/cart/cartrpc/pb/cartRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *cartRpc.UpRequest) (*cartRpc.Response, error) {
	// todo: add your logic here and delete this line
	HKeY := "cart:user_id" + fmt.Sprintf("%d", in.UserId)
	LKey := "Number:good_id" + fmt.Sprintf("%d", in.GoodId)
	//根据 商品id 查数据
	g := dao.MyId(in.GoodId)
	//进行修改 首先 判断这个商品是否存在购物车内 不存在 这添加
	if !utils.RedisHex(HKeY, in.GoodId) {
		num, err := utils.RedisLLen(LKey)
		if err == false || num < in.Count {
			return &cartRpc.Response{
				Msg:  "库存不足",
				Code: http.StatusAccepted,
			}, nil
		}
		//求出总价
		totalAmount := g.Price * float64(in.Count)
		//库存充足 进行添加购物车
		c := model.Cart{
			Count:       in.Count,
			TotalAmount: totalAmount,
			G:           g,
		}
		//减少库存
		for i := 1; i <= int(in.Count); i++ {
			utils.RedisLPop(LKey)
		}
		//储存
		if !utils.RedisHSet(HKeY, c, in.GoodId) {
			return &cartRpc.Response{
				Msg:  "添加失败",
				Code: http.StatusAlreadyReported,
			}, nil
		}
		return &cartRpc.Response{
			Msg:  "修改成功",
			Code: http.StatusOK,
		}, nil
	}
	//获取以前的购物车数据
	c := utils.RedisHGet(HKeY, in.GoodId)
	fmt.Println(c)
	//判断操作
	logs.Info(in.Type)
	if in.Type == "add" {
		num, err := utils.RedisLLen(LKey)
		if err == false || num < in.Count {
			return &cartRpc.Response{
				Msg:  "库存不足",
				Code: http.StatusAccepted,
			}, nil
		}
		c.Count += in.Count
		c.TotalAmount = float64(c.Count) * g.Price
		utils.RedisHSet(HKeY, c, in.GoodId)
		//减少库存
		for i := 1; i <= int(c.Count); i++ {
			utils.RedisLPop(LKey)
		}
	}
	if in.Type == "down" {
		c.Count -= in.Count
		c.TotalAmount = float64(c.Count) * g.Price
		utils.RedisHSet(HKeY, c, in.GoodId)
		//回滚库存
		if c.Count <= 0 {
			utils.RedisDel(HKeY, in.GoodId)
		}
		for i := 1; i <= int(in.Count); i++ {
			utils.RedisLPush(LKey)
		}
	}

	return &cartRpc.Response{
		Msg:  "修改成功",
		Code: http.StatusOK,
	}, nil
}
